/**
 * 用不上这破工具了
 * 这里有完整的pbf文件
 * https://github.com/Mammoth777/fonts.pbf
 */

import fs from 'fs';
import path from 'path';
import axios from 'axios';
import { MapboxToken } from '../config.js';

const currentDir = path.dirname(import.meta.url).replace('file://', '');

function getToken() {
  return MapboxToken;
}

const fontStacks = ['Open Sans Regular', 'Arial Unicode MS Regular'];
const ranges = [
  '0-255',
  '256-511',
  '512-767',
  '768-1023',
  '1024-1279',
  '1280-1535',
  '1536-1791',
  '1792-2047',
  '2048-2303',
  '2304-2559',
  '2560-2815',
  '2816-3071',
  '3072-3327',
  '3328-3583',
  '3584-3839',
  '3840-4095',
  // 下面的似乎用不上， 还没理解这里的range是怎么算的
  // '13312-19903', // CJK Unified Ideographs Extension A (0x3400-0x4DBF)
  // '19904-40959', // CJK Unified Ideographs (0x4E00-0x9FFF)
  // '131072-173791', // CJK Unified Ideographs Extension B (0x20000-0x2A6DF)
  // '173824-177983', // CJK Unified Ideographs Extension C (0x2A700-0x2B73F)
  // '177984-178207', // CJK Unified Ideographs Extension D (0x2B740-0x2B81F)
  // '178208-183983', // CJK Unified Ideographs Extension E (0x2B820-0x2CEAF)
  // '183984-191471'  // CJK Unified Ideographs Extension F (0x2CEB0-0x2EBEF)
];

const baseUrl = 'https://api.mapbox.com/fonts/v1/mapbox';
const accessToken = getToken();

async function downloadFont(fontStack, range) {
  const url = `${baseUrl}/${encodeURIComponent(fontStack)}/${range}.pbf?access_token=${accessToken}`;
  const outputPath = path.join(currentDir, 'fonts', fontStack, `${range}.pbf`);

  try {
    const response = await axios.get(url, { responseType: 'arraybuffer' });
    fs.mkdirSync(path.dirname(outputPath), { recursive: true });
    fs.writeFileSync(outputPath, response.data);
    console.log(`Downloaded ${fontStack} ${range}`);
  } catch (error) {
    console.error(`Failed to download ${fontStack} ${range}:`);
  }
}

async function downloadFonts() {
  for (const fontStack of fontStacks) {
    for (const range of ranges) {
      await downloadFont(fontStack, range);
    }
  }
}

function main() {
  console.log('start download');
  downloadFonts();
}
main();
